package cn.edu.zut.web;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.zut.service.EmployeeService;
import cn.edu.zut.domain.Employee;

@RestController
public class LoginController {
    private EmployeeService employeeService;

    @RequestMapping(value = "/index.html")
    public String loginPage(){
        return "login";
    }

    @RequestMapping(value = "/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request,LoginCommand loginCommand){
        boolean isValidUser =  employeeService.hasMatchEmployee(loginCommand.getEmployeeName(),
                loginCommand.getPassword());
        if (!isValidUser) {
            return new ModelAndView("login", "error", "用户名或密码错误。");
        } else {

            Employee employee = employeeService.findEmployeeByEmployeeName(loginCommand
                    .getEmployeeName());
            employee.setLastIp(request.getLocalAddr());
            employee.setLastVisit(new Date());
            employeeService.loginSuccess(employee);
            request.getSession().setAttribute("employee", employee);
            return new ModelAndView("main");
        }
    }

    @Autowired
    public void setUserService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }



}
